import getpass,tkinter,tkinter.messagebox,tkinter.ttk
import os,threading
import webbrowser
import crawler_public,language_crawler_chs,noval_website_functions

username = getpass.getuser()
make_dir = 'C:\\Users\\' + username + '\\Documents\\DA_Tools\\'
crawler_path = make_dir + 'crawler_book_temp\\'
if not os.path.exists(crawler_path):
    os.makedirs(crawler_path)
# 发送小说指令标识
noval_name_number_send_path = crawler_path + 'noval_name_number_send_flag.log'
# 记录下载序号临时文件
noval_name_number_path = crawler_path + 'noval_name_number.log'
# 本地下载指令标识
local_download_path = crawler_path + 'local_download_flag.log'
# 记录网盘链接
noval_pan_link_path = crawler_path + 'noval_pan_link.log'
# 记录本地下载真实地址
zxcs_local_download_url_path = crawler_path + 'zxcs_local_download_url.log'
crawler_book_version_path = crawler_public.resource_path(os.path.join('version/crawler_book_version', 'version_history.txt'))
with open(local_download_path,'w') as fp:
    fp.write('0')
# 统一修改版本号
book_version = 'V1.0.0'
book_version_code = 100
# 统一修改frame的宽高
width = 600
height = 428
# 统一按钮宽度
width_button = 20
# 初始化语言对象
languages = language_crawler_chs.Language_Crawer()
languages_all = languages.all_languages_crawer()
# 统一root窗口总宽高
main_width = 600
main_height = 450

class Context:
    pass

class CrawlerBook(object):
    @crawler_public.crawler_tools_log
    def book_frame(self,root,root_label_frame,crawler_book_frame,main_version):
    # def book_frame(self):
        self.root = root
        self.root_label_frame = root_label_frame
        self.crawler_book_frame = crawler_book_frame
        self.main_version = main_version
        # self.root = tkinter.Tk()
        LOGO_path = crawler_public.resource_path(os.path.join('icon', 'book.ico'))
        self.root.title(languages_all['crawler_book_name'] + ' ' + book_version + ' ' + languages_all['platform'])
        self.root.iconbitmap(LOGO_path)

        # screenWidth = self.root.winfo_screenwidth()
        # screenHeight = self.root.winfo_screenheight()
        # w = main_width
        # h = main_height
        # x = (screenWidth - w) / 2
        # y = (screenHeight - h) / 2
        # self.root.geometry('%dx%d+%d+%d' % (w, h, x, y))

        # self.root.resizable(0, 0)

        self.book_menu_bar()
        self.crawler_website_frame()
        # self.root.mainloop()

    def book_menu_bar(self):
        # 切换窗口（选择模式）
        self.crawler_book_frame_1 = tkinter.Frame(self.root, width=main_width, height=main_height)

        self.main_frame = tkinter.Frame(self.crawler_book_frame_1, width=380, height=20)
        self.main_menu = tkinter.Menubutton(self.main_frame, text=languages_all['book_website_name'])
        self.main_menu1 = tkinter.Menubutton(self.main_frame, text=languages_all['book_website_name'])
        self.main_menu1.place(x=0, y=0)
        self.main_menu1.config(state='disable')
        self.main_menu.bind('<Button-1>', lambda x: self.display_crawler_book_frame())

        # 历史版本
        self.main_history_label = tkinter.Label(self.main_frame, text='历史版本')
        self.main_history_label_disbale = tkinter.Label(self.main_frame, text='历史版本')
        self.main_history_label_disbale.config(state='disable')
        self.main_history_label.place(x=100, y=2)
        self.main_history_label.bind('<Button-1>', lambda x: self.display_history_frame())

        self.main_frame.place(x=0, y=0)

        # 退出按钮
        self.exit_button = tkinter.Button(self.crawler_book_frame_1,width=width_button,text=languages_all['exit_crawler_text'],bg='blue',fg='#ffffff')
        self.exit_button_disable = tkinter.Button(self.crawler_book_frame_1,width=width_button,text=languages_all['exit_crawler_text']
                                                  ,bg='red',fg='#ffffff')
        self.exit_button_disable.config(state='disable')
        self.exit_button.place(x=450,y=0)
        self.exit_button.bind('<Button-1>',lambda x:self.close_crawler_book_bind())

        self.crawler_book_frame_1.place(x=0, y=0)

    def display_history_frame(self):
        # 显示历史版本页面
        self.display_main_history()

        # 默认其他页面的两个都要换
        self.main_menu1.place_forget()
        self.main_menu.place(x=0, y=0)
        self.main_history_label.place_forget()
        self.main_history_label_disbale.place(x=100, y=2)

        try:
            self.website_info_frame.place_forget()
            self.website_frame.place_forget()
        except AttributeError:
            pass

    def display_crawler_book_frame(self):
        # 显示爬取小说工具页面
        self.crawler_website_frame()

        # 默认其他页面的两个都要换
        self.main_menu.place_forget()
        self.main_menu1.place(x=0, y=0)
        self.main_history_label_disbale.place_forget()
        self.main_history_label.place(x=100, y=2)

        try:
            self.main_history_frame.place_forget()
        except AttributeError:
            pass

    def display_main_history(self):
        # 历史版本页面逻辑
        self.main_history_frame = tkinter.Frame(self.root, width=600, height=350)
        self.main_history = tkinter.Frame(self.main_history_frame)
        self.scrollbar = tkinter.Scrollbar(self.main_history)
        self.version_listbox = tkinter.Listbox(self.main_history, width=55, height=20, yscrollcommand=(self.scrollbar.set))
        self.version_listbox.bindtags((self.version_listbox, 'all'))
        self.scrollbar.config(command=(self.version_listbox.yview))
        self.scrollbar.pack(side=(tkinter.RIGHT), fill=(tkinter.Y))
        self.version_listbox.pack()
        version_read = open(crawler_book_version_path, 'r', encoding='utf-8',errors='ignore')
        for readline in version_read.readlines():
            self.version_listbox.insert(tkinter.END, readline)
        self.main_history.place(x=5,y=10)
        self.main_history_frame.place(y=50)

    def crawler_website_frame(self):
        # 指定网站爬书
        # 信息输出框
        self.website_info_frame = tkinter.Frame(self.crawler_book_frame_1,width=300,height=height)
        # self.scrollbar = tkinter.Scrollbar(self.verion_frame)
        self.website_info_scrollbar = tkinter.Scrollbar(self.website_info_frame)
        self.website_info_text = tkinter.Text(self.website_info_frame, yscrollcommand=(self.website_info_scrollbar.set), width=43,
                                          height=32,bg='black',fg='#ffffff',
                                          font=('宋体', 10))
        self.website_info_scrollbar.config(command=self.website_info_text.yview)
        self.website_info_scrollbar.pack(side=(tkinter.RIGHT), fill=(tkinter.Y))
        self.website_info_text.config(state='disable')  # 设为disable防止Text多行文本框能被点击
        self.website_info_text.pack()
        self.website_info_frame.place(y=25)

        # 指定网站
        self.website_frame = tkinter.Frame(self.crawler_book_frame_1,width=300,height=height)

        # 指定网站label
        self.website_label = tkinter.Label(self.website_frame,text=languages_all['select_book_download_website'],fg='red')
        self.website_label.place(x=5,y=0)

        # 指定网站列表
        website_list = [languages_all['zxcs_book_name']]
        self.noval_website_value = tkinter.StringVar()
        self.noval_website_combobox = tkinter.ttk.Combobox(self.website_frame,textvariable=self.noval_website_value,state="readonly", width=30)
        self.noval_website_combobox['value'] = website_list
        self.noval_website_combobox.current(0)
        self.noval_website_combobox.place(x=5,y=30)

        # 输入搜索的小说名称
        # label
        self.noval_name_label = tkinter.Label(self.website_frame, text=languages_all['input_book_name'],
                                           fg='red')
        self.noval_name_label.place(x=5, y=60)
        # entry
        self.noval_name = tkinter.StringVar()
        self.noval_name_entry = tkinter.Entry(self.website_frame,textvariable=self.noval_name,width=35)
        self.noval_name_entry.place(x=5,y=90)

        # 选择下载的小说序号
        # label
        self.noval_name_label_1 = tkinter.Label(self.website_frame, text=languages_all['input_book_name_number'],
                                              fg='red')
        self.noval_name_label_1.place(x=5, y=120)
        # entry
        self.noval_name_number = tkinter.IntVar()
        self.noval_name_entry_1 = tkinter.Entry(self.website_frame, textvariable=self.noval_name_number, width=20)
        self.noval_name_entry_1.place(x=5, y=150)
        self.noval_name_entry_1.config(state='disable')
        self.noval_name_number.set(1)

        # 发送序号按钮
        self.noval_name_number_send = tkinter.Button(self.website_frame, width=width_button-5,
                                             text=languages_all['noval_name_number_send_text'])
        self.noval_name_number_send_disable = tkinter.Button(self.website_frame, width=width_button-5,
                                                     text=languages_all['noval_name_number_send_text'])
        self.noval_name_number_send_disable.config(state='disable')
        self.noval_name_number_send_disable.place(x=155, y=150)
        self.noval_name_number_send.bind('<Button-1>',lambda x:self.noval_number_send_bind())

        # 获取小说的网盘和密码
        # label
        self.noval_pan_link_and_pwd_label = tkinter.Label(self.website_frame, text=languages_all['get_pan_link_passwd'],
                                                fg='red')
        self.noval_pan_link_and_pwd_label.place(x=5, y=180)
        # entry1
        self.noval_name_link = tkinter.StringVar()
        self.noval_pan_link_entry = tkinter.Entry(self.website_frame, textvariable=self.noval_name_link, width=35)
        self.noval_pan_link_entry.place(x=5, y=210)
        self.noval_name_link.set(languages_all['get_pen_link'])
        self.noval_pan_link_entry.config(state='disable')
        # entry2
        self.noval_name_pwd = tkinter.StringVar()
        self.noval_pan_pwd_entry = tkinter.Entry(self.website_frame, textvariable=self.noval_name_pwd, width=35)
        self.noval_pan_pwd_entry.place(x=5, y=240)
        self.noval_name_pwd.set(languages_all['get_pen_pwd'])
        self.noval_pan_pwd_entry.config(state='disable')

        # 网盘链接、提取码按钮与本地下载按钮
        self.noval_pan_link_and_pwd_str = tkinter.StringVar()
        self.noval_pan_link_and_pwd_button = tkinter.Button(self.website_frame,textvariable=self.noval_pan_link_and_pwd_str)
        self.noval_pan_link_and_pwd_button_disable = tkinter.Button(self.website_frame,textvariable=self.noval_pan_link_and_pwd_str)
        self.noval_pan_link_and_pwd_button_disable.config(state='disable')
        # self.noval_pan_link_and_pwd_button.place(x=5, y=215)
        self.noval_pan_link_and_pwd_button.bind('<Button-1>',lambda x:self.noval_pan_link_and_pwd_bind())

        self.noval_local_download_button = tkinter.Button(self.website_frame, text='本地下载',width=15)
        self.noval_local_download_button_disable = tkinter.Button(self.website_frame,text='本地下载',width=15)
        self.noval_local_download_button_disable.config(state='disable')
        # self.noval_local_download_button.place(x=150, y=215)
        self.noval_local_download_button.bind('<Button-1>', lambda x: self.noval_local_download_bind())

        # 点击开始
        self.noval_get_start = tkinter.Button(self.website_frame,width=width_button-5,text=languages_all['get_book_start'])
        self.noval_get_start_disable = tkinter.Button(self.website_frame,width=width_button-5,text='正在运行中...')
        self.noval_get_start_disable.config(state='disable')
        self.noval_get_start.bind('<Button-1>',lambda x:self.select_book_website_bind())
        self.noval_get_start.place(x=5,y=270)

        # 点击停止
        self.noval_get_stop = tkinter.Button(self.website_frame, width=width_button - 5,
                                              text=languages_all['get_book_stop'])
        self.noval_get_stop_disable = tkinter.Button(self.website_frame, width=width_button - 5,
                                                      text=languages_all['get_book_stop'])
        self.noval_get_stop_disable.config(state='disable')
        self.noval_get_stop_disable.place(x=150, y=270)

        # 使用说明
        self.book_website_label = tkinter.Label(self.website_frame, text=languages_all['book_Instructions'],
                                                fg='red')
        self.book_website_label.place(x=5, y=300)

        self.website_frame.place(x=318,y=25)

    def select_book_website_bind(self):
        # 选择网站
        def t_select_book_website():
            self.noval_get_start_disable.place(x=5, y=270)
            self.noval_get_stop.place(x=150, y=270)
            self.search_website_book_bind()
            self.noval_get_start_disable.place_forget()
            self.noval_get_stop.place_forget()

        t_select_book_website = threading.Thread(target=t_select_book_website)
        t_select_book_website.setDaemon(True)
        setattr(Context,"t_select_book_website",t_select_book_website)
        t_select_book_website.start()

    def noval_number_send_bind(self):
        # 发送小说序号指令
        def t_noval_number_send():
            self.noval_name_number_send.place_forget()
            self.noval_name_number_send_disable.place(x=155, y=150)
            try:
                with open(noval_name_number_path,'w') as fp:
                    fp.write(str(self.noval_name_number.get()))
            except Exception:
                pass
            noval_name_number = open(noval_name_number_path,'r').read()
            if noval_name_number.strip() == '':
                tkinter.messagebox.showerror(title='输入错误',message='不能发送空内容，请按要求重新输入正确无误的序号！！！')
                self.noval_name_number_send_disable.place_forget()
                self.noval_name_number_send.place(x=155, y=150)
            else:
                with open(noval_name_number_send_path, 'w') as fp:
                    fp.write('True')

        t_noval_number_send = threading.Thread(target=t_noval_number_send)
        t_noval_number_send.setDaemon(True)
        setattr(Context, "t_noval_number_send", t_noval_number_send)
        t_noval_number_send.start()

    def search_website_book_bind(self):
        # 请求知轩藏书网站
        """
        需要传的参数如下：
        website_info_text 信息输出框
        noval_name 获取小说名称
        noval_name_number 小说下载序号
        self.noval_name_entry_1 下载小说序号entry
        noval_name_number_send 发送指令按钮
        noval_name_number_send_disable 发送指令按钮disable
        noval_pan_link_entry 网盘链接输入框
        noval_pan_pwd_entry  提取码输入框
        noval_name_link     网盘链接
        noval_name_pwd      提取码
        noval_name_entry  小说名称输入框
        website_label 指定网站的Label
        noval_name_label 小说名称label
        noval_name_label_1 序号label
        noval_pan_link_and_pwd_label 网盘链接和密码label
        noval_website_value 指定的网站名称
        noval_pan_link_and_pwd_button  网盘链接和链接地址点击按钮
        noval_pan_link_and_pwd_button_disable 网盘链接和链接地址禁用按钮
        noval_pan_link_and_pwd_str 网盘链接和链接地址按钮text
        noval_local_download_button 本地下载点击按钮
        noval_local_download_button_disable 本地下载禁用按钮
        """
        with open(noval_name_number_send_path,'w') as fp:
            fp.write('False')
        noval_website_functions.book_website_function(
            self.website_info_text,
            self.noval_name.get().strip(),
            self.noval_name_number,
            self.noval_name_entry_1,
            self.noval_name_number_send,
            self.noval_name_number_send_disable,
            self.noval_pan_link_entry,
            self.noval_pan_pwd_entry,
            self.noval_name_link,
            self.noval_name_pwd,
            self.noval_name_entry,
            self.website_label,
            self.noval_name_label,
            self.noval_name_label_1,
            self.noval_pan_link_and_pwd_label,
            self.noval_website_value.get().strip(),
            self.noval_pan_link_and_pwd_button,
            self.noval_pan_link_and_pwd_button_disable,
            self.noval_pan_link_and_pwd_str,
            self.noval_local_download_button,
            self. noval_local_download_button_disable
        )

    def noval_pan_link_and_pwd_bind(self):
        # 网盘链接和链接地址点击按钮
        def t_noval_pan_link_and_pwd():
            self.noval_pan_link_and_pwd_button.place_forget()
            self.noval_pan_link_and_pwd_button_disable.place(x=5, y=215)
            noval_pan_link = open(noval_pan_link_path,'r').read()
            crawler_public.pyperclip_copy_paste(noval_pan_link)
            self.noval_pan_link_and_pwd_button_disable.place_forget()
            self.noval_pan_link_and_pwd_button.place(x=5, y=215)

        t_noval_pan_link_and_pwd = threading.Thread(target=t_noval_pan_link_and_pwd)
        t_noval_pan_link_and_pwd.setDaemon(True)
        t_noval_pan_link_and_pwd.start()

    def noval_local_download_bind(self):
        # 本地下载点击按钮
        def t_noval_local_download():
            self.noval_local_download_button.place_forget()
            self.noval_local_download_button_disable.place(x=150, y=215)
            noval_local_download_url = open(zxcs_local_download_url_path,'r').read()
            webbrowser.open(noval_local_download_url)
            self.noval_local_download_button_disable.place_forget()
            self.noval_local_download_button.place(x=150, y=215)

        t_noval_local_download = threading.Thread(target=t_noval_local_download)
        t_noval_local_download.setDaemon(True)
        t_noval_local_download.start()

    def close_crawler_book_bind(self):
        def t_close_crawler_book():
            # 退出小说分享工具
            # 销毁当前的frame
            self.exit_button.place_forget()
            self.exit_button_disable.place(x=450,y=0)
            if tkinter.messagebox.askokcancel(title='退出工具',message='是否退出 免费分享小说工具？'):
                self.crawler_book_frame_1.place_forget()
                # 先结束所有线程
                try:
                    crawler_public.stop_thread(getattr(Context,"t_select_book_website"))
                    crawler_public.stop_thread(getattr(Context,"t_noval_number_send"))
                    print('已结束线程！')
                except Exception:
                    print('无需结束线程！')
                # 显示主菜单
                self.root_label_frame.place(x=0,y=0)
                self.crawler_book_frame()
                # 还原图标
                main_logo = crawler_public.resource_path(os.path.join('icon', 'my-da.ico'))
                self.root.iconbitmap(main_logo)
                # 还原标题
                self.root.title('DA万能工具' + self.main_version + ' Windows版')
            else:
                self.exit_button_disable.place_forget()
                self.exit_button.place(x=450, y=0)

        t_close_crawler_book = threading.Thread(target=t_close_crawler_book)
        t_close_crawler_book.setDaemon(True)
        t_close_crawler_book.start()

